<template>
  <el-dialog class="register" title="用户注册" :visible.sync="isShow" width="600px" :show-close="false">
    <div slot="title" class="title">用户注册</div>
    <div slot="footer" class="footer">
      <el-button @click="isShow=false">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
    <el-form :model="form" label-width="100px" ref="form" :rules="rules">
      <el-form-item label="头像" class="upload-avatar" prop="avatar">
        <!-- 上传组件 el-upload
                  action:上传接口地址
                  name:上传文件对应的参数名
                  show-file-list:true:显示列表 false:不显示列表
                  before-upload:上传前  function(file){file.type:文件类型  file.size:文件大小
                           用于上传前文件类型与大小限制 
                           return boolean值  
                                 true:正常上传
                                 false:中止上传
                         }
                 on-success:上传成功处理 function(res,file){
                      res:上传成功后接口返回值
                      file: file.response:等效于res
                            file.raw:文件的file对象
                       }
            自定义表单验证
            rules:{
            prop值:[
            {required:true,message:"错误信息",trigger:"change/blur"},{
                min:最小长度,max:最大长度,message:"错误信息",trigger:"change/blur"
            },{
                validator:(rule,value,callback)=>{
                    rule:当前规则
                    value:当前验证项的值
                    callback:验证通过  callback()
                            验证不通过  callback(new Error("错误信息"))
                注意验证通过一定要callback()   验证不通过  callback(new Error("错误信息")) 
                },
                trigger:"change/blur"
              }
            ]
         }
        -->

        <el-upload
          class="avatar-uploader"
          :action="baseUrl+'/uploads'"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.avatar" :src="baseUrl+'/' + form.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="图形码" prop="code">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.code"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <img @click="changeCode" class="code-pic" :src="baseUrl + codeimgUrl" alt />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.rcode"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <el-button @click="getCode" :disabled="totalTime!=6"
            >获得用户验证码 <span v-if="totalTime!=6"
            >({{totalTime}}s)</span></el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { getCodeApi,toRegister } from '@/api/register.js'
export default {
  // 关闭窗口时(isShow=false),重置表单数据
  watch: {
    isShow(newVel){
      if (newVel== false) {
        // 重置表单：访问el-form的this,调用它的resetFields方法
        this.$refs.form.resetFields();
      }
    }
  },
  data() {
    return {
      isShow: false,
      codeimgUrl:'/captcha?type=sendsms',
      totalTime:6,
      form: {
        avatar: '',
        username: '',
        email: '',
        phone: '',
        password: '',
        code: '',
        rcode: '',
      },
      rules: {
        avatar: [{ required: true, message: '请输入头像', trigger: 'change' }],
        username: [
          { required: true, message: '请输入用户名', trigger: 'change' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let _reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
              if (_reg.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正确邮箱'))
              }
            },
            trigger: 'change',
          },
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let _reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              if (_reg.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正确手机号'))
              }
            },
            trigger: 'change',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
        ],
        code: [{ required: true, message: '请输入图形码', trigger: 'change' }],
        rcode: [{ required: true, message: '请输入验证码', trigger: 'change' }],
      },
      // imageUrl: '',
      baseUrl: process.env.VUE_APP_URL,
    }
  },
  methods: {
    handleAvatarSuccess(res) {
      window.console.log(res)
      // this.imageUrl = res.data.file_path
      this.form.avatar = res.data.file_path
      // this.imageUrl = URL.createObjectURL(file.raw)
      // 局部验证
      this.$refs.form.validateField(['avatar'])
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    submit() {
      this.$refs.form.validate((result) => {
        if (result) {
          toRegister(this.form).then(res=>{
            window.console.log(res);
            // if(res.data.code==200){
              this.$message.success('注册成功');
              this.isShow = false
            // }
          })
          // this.$message.success('验证成功')
        // } else {
        //   this.$message.error('验证失败')
        }
      })
    },
    changeCode(){
      this.codeimgUrl = '/captcha?type=sendsms&ftduy=' + Math.random()*999;
    },
    getCode(){
      let num = 0;
      this.$refs.form.validateField(['phone','code'],(errorMessage)=>{
        if(errorMessage==""){
          num++;
        }
      });
       if (num == 2) {
        //  倒计时 totalTime=5
        this.totalTime--;
        let _time = setInterval(()=>{
          this.totalTime--;
          if(this.totalTime<0){
            // 清除定时器
            clearInterval(_time);
            // 还原时间
            this.totalTime = 6
          }
        },1000)
        //  this.$axios({
        //    url:'sendsms',
        //    method:'post',
        //    data:{
        //      code:this.form.code,
        //      phone:this.form.phone
        //    }
        //  }).then(res =>{
        //    window.console.log(res);
        //    this.$message.success(res.data.data.captcha + '')
        //  })
         getCodeApi({
             code:this.form.code,
             phone:this.form.phone
         }).then(res =>{
          //  window.console.log(res);
           this.$message.success(res.data.data.captcha + '')
         }).catch(()=>{})
          // this.$message.success('验证通过')
        }
    }
  },
}
</script>

<style lang="less">
.register {
  .title {
    height: 53px;
    line-height: 53px;
    text-align: center;
    color: #fff;
    background: linear-gradient(to right, #01c5fa, #1493fa);
  }
  .el-dialog__header {
    padding: 0;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .upload-avatar {
    text-align: center;
  }
  .code-pic {
    width: 100%;
    height: 40px;
  }
}
</style>